package mysql;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import objects.Location;

public class LocationQueries {

	private static final String DATABASE_URL = "jdbc:mysql://localhost/MovieBase";
	private static final String USERNAME = "moviebase";
	private static final String PASSWORD = "moviebase";

	private Connection connection = null;
	private PreparedStatement selectAllLocations = null;
	private PreparedStatement insertNewLocation = null;
	
	public LocationQueries() {
		try {
			connection = DriverManager.getConnection(DATABASE_URL, USERNAME,
					PASSWORD);

			selectAllLocations = connection
					.prepareStatement("SELECT * FROM Locations"/*"Select L.address from Locations L where lid = ?"*/);

			insertNewLocation = connection
					.prepareStatement("INSERT INTO Locations (`lid`, address,state) VALUES "
							+ "(?,?,?)");
			
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

	public List<Location> getAllLocations() {
		List<Location> results = null;
		ResultSet resultSet = null;

		try {
			resultSet = selectAllLocations.executeQuery();
			results = new ArrayList<Location>();

			while (resultSet.next()) {
				results.add(new Location(resultSet.getInt("lid"), resultSet
						.getString("address"), resultSet.getString("state")));
			}
		} catch (SQLException e) {
			System.out.println(e);
		} finally {
			try {
				resultSet.close();
			} catch (SQLException e) {

			}
		}
		return results;
	}

	public int addLocation(int locid, String address, String state) {
		int result = 0;

		try {
			insertNewLocation.setInt(1, locid);
			insertNewLocation.setString(2, address);
			insertNewLocation.setString(3, state);

			result = insertNewLocation.executeUpdate();
		} catch (SQLException e) {
			System.out.println(e);
			close();
		}

		return result;
	}

	public void close() {
		try {
			connection.close();
		} catch (SQLException e) {
			System.out.println(e);
		}
	}

}